// https://www.lintcode.com/problem/binary-tree-zigzag-level-order-traversal/description

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: A Tree
     * @return: A list of lists of integer include the zigzag level order traversal of its nodes' values.
     */
    
    // 法一：用自定义节点标记结尾
    // vector<vector<int>> zigzagLevelOrder(TreeNode * root) {
    //     vector<vector<int>> result;
    //     if (!root) return result;
    //     queue<TreeNode *> q;
    //     vector<int> tmp_vec;
    //     q.push(root);
    //     q.push(new TreeNode(-1));
    //     // bool flag = true;
    //     int flag     = 1;
    //     while (!q.empty())
    //     {
    //         TreeNode* tmp = q.front();
    //         q.pop();
    //         if (tmp->val != -1) 
    //         {
    //             tmp_vec.push_back(tmp->val);
    //             if (tmp->left) q.push(tmp->left);
    //             if (tmp->right) q.push(tmp->right);
    //         }
    //         else
    //         {
    //             if (flag) result.push_back(tmp_vec);
    //             else
    //             {
    //                 reverse(tmp_vec.begin(), tmp_vec.end());
    //                 result.push_back(tmp_vec);
    //             }
    //             // flag = ~ flag; 这个位操作，不好改bool类型
    //             // flag = !flag;
    //             flag ^= 1;
    //             tmp_vec.clear();
    //             if (q.empty()) break;
    //             else q.push(new TreeNode(-1));
    //         }
    //     }
    //     return result;
    // }
    
    // 法二：每一轮记录长度
    vector<vector<int>> zigzagLevelOrder(TreeNode * root) {
        vector<vector<int>> result;
        if (!root) return result;
        queue<TreeNode *> q;
        q.push(root);
        bool flag = true;
        while (!q.empty())
        {
            int len = q.size();
            vector<int> tmp_vec;
            for (int i = 0; i < len; ++i)
            {
                TreeNode * tmp = q.front();
                tmp_vec.push_back(tmp->val);
                q.pop();
                if (tmp->left) q.push(tmp->left);
                if (tmp->right) q.push(tmp->right);
            }
            if (!flag) reverse(tmp_vec.begin(), tmp_vec.end());
            result.push_back(tmp_vec);
            flag = !flag;
        }
        return result;
    }
    
};